package net.tooeye.easyplus.easyplus.activities;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;


import net.tooeye.easyplus.easyplus.R;
import net.tooeye.easyplus.easyplus.common.NetworkUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private BarChart barChart;
    private YAxis leftAxis;
    private YAxis rightAxis;
    private XAxis xAxis;
    private LinearLayout layoutScan,layoutCustomScan,layoutInputSfcta;
    private  String host,token;
    private TextView textViewCoptdCount,textViewMoctaCount,textViewInvmcCount,textViewCoptgCount;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ActionBar bar = getSupportActionBar();
        if (bar != null){
            bar.hide();
        }

        barChart = findViewById(R.id.barChart);
        layoutScan = findViewById(R.id.layoutScan);
        layoutScan.setOnClickListener(this);
        layoutCustomScan = findViewById(R.id.layoutCustomScan);
        layoutCustomScan.setOnClickListener(new CustomScan());
        layoutInputSfcta = findViewById(R.id.inputSfcta);
        layoutInputSfcta.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent  = new Intent(MainActivity
                        .this,SfctaActivity.class);
                intent.putExtra("bar","");
                startActivity(intent);
            }
        });
        SharedPreferences sp = getSharedPreferences("easy_plus", Context.MODE_PRIVATE);
        token =sp.getString("token","");
        host =sp.getString("host","");
        textViewCoptdCount = findViewById(R.id.textViewCoptdCount);
        textViewMoctaCount = findViewById(R.id.textViewMoctaCount);
        textViewInvmcCount = findViewById(R.id.textViewInvmcCount);
        textViewCoptgCount = findViewById(R.id.textViewCoptgCount);
        initChart();
        initCount();
    }

    private void initCount() {
        String url = "http://" + host + "/api/sale/count?token=" + token;
        @SuppressLint("HandlerLeak") Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject((String)msg.obj);
                    textViewCoptdCount.setText(jsonObject.getInt("coptdCount")+"");
                    textViewMoctaCount.setText(jsonObject.getInt("moctaCount")+"");
                    textViewInvmcCount.setText(jsonObject.getString("invmcCount"));
                    textViewCoptgCount.setText(jsonObject.getString("copthCount"));

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        };
        NetworkUtil.getInstance().get(MainActivity.this,url,null,handler,1,"");

    }

    private void initChart() {
        leftAxis = barChart.getAxisLeft();
        rightAxis = barChart.getAxisRight();
        xAxis = barChart.getXAxis();
        xAxis.setDrawGridLines(false);
        rightAxis.setDrawGridLines(false);
        leftAxis.setDrawGridLines(true);
        rightAxis.setEnabled(false);
        leftAxis.setEnabled(false);
        //背景颜色
        barChart.setBackgroundColor(Color.WHITE);
        //网格
        barChart.setDrawGridBackground(false);
        //背景阴影
        barChart.setDrawBarShadow(false);
        //显示边界
        barChart.setDrawBorders(true);
        //设置动画效果
        barChart.animateY(1000, Easing.EasingOption.Linear);
        barChart.animateX(1000, Easing.EasingOption.Linear);
        //折线图例 标签 设置
        Legend legend = barChart.getLegend();
        legend.setForm(Legend.LegendForm.LINE);
        legend.setTextSize(11f);
        legend.setPosition(Legend.LegendPosition.ABOVE_CHART_LEFT);
        //显示位置
        //XY轴的设置
        //X轴设置显示位置在底部
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        String url = "http://" + host + "/api/sale/YearSale?token=" + token;
        @SuppressLint("HandlerLeak") Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject((String)msg.obj);
                    JSONArray jsonArray  = jsonObject.getJSONArray("values");
                    JSONArray jsonMonths  = jsonObject.getJSONArray("months");
                    List<Float> yValue = new ArrayList<>();
                    List<String> xValues = new ArrayList<>();
                    for (int i = 0; i < jsonArray.length(); i++) {
                        double jd = jsonArray.getDouble(i);
                        yValue.add((float)jd);
                        xValues.add(jsonMonths.getString(i));
                    }
                    ArrayList<BarEntry> yValues = new ArrayList<BarEntry>();
                    for (int i = 0; i < yValue.size(); i++) {
                        yValues.add(new BarEntry(yValue.get(i), i));
                    }
                    BarDataSet barDataSet = new BarDataSet(yValues, "本年度分月销售");
                    barDataSet.setColor(0xff0099cc);
                    ArrayList<BarDataSet> barDataSets = new ArrayList<BarDataSet>();
                    barDataSets.add(barDataSet); // add the datasets
                    BarData barData = new BarData(xValues, barDataSet);
                    barChart.setData(barData);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        };
        NetworkUtil.getInstance().get(MainActivity.this,url,null,handler,1,"");

    }

    @Override
    public void onClick(View view) {
        new IntentIntegrator(this)
                .setPrompt("请对准一维或二维码")
                .setCaptureActivity(ScanActivity.class)
                .setCameraId(0)

                .setBeepEnabled(true)
                .initiateScan();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if(result != null) {
            if(result.getContents() == null) {

            } else {
                 Intent intent  = new Intent(MainActivity
                 .this,SfctaActivity.class);
                 intent.putExtra("bar",result.getContents()+"");
                 startActivity(intent);
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    //连续扫描
    class CustomScan implements View.OnClickListener{
        @Override
        public void onClick(View v) {
            new IntentIntegrator(MainActivity.this)
                    .setCaptureActivity(CustomScanActivity.class)
                    .setCameraId(0)
                    .setBeepEnabled(true)
                    .initiateScan();
        }
    }
}
